<template>
  <div class="padding-16">
    <a-card class="general-card" title="字典数据管理">
      <a-form
        ref="refSearchForm"
        :model="searchForm"
        auto-label-width
      >
        <a-row :gutter="16">
          <a-col :span="6">
            <a-form-item field="dict_id" label="字典名称">
              <a-select
                v-model="searchForm.dict_id"
                :field-names="fieldNames"
                :options="dictOptions"
                placeholder="请输入字典名称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="name" label="数据名称">
              <a-input v-model="searchForm.name" placeholder="请输入数据名称" />
            </a-form-item>
          </a-col>

          <a-col :span="6">
            <a-form-item field="status" label="状态">
              <a-select v-model="searchForm.status" :options="statusOptions" placeholder="全部" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-space :size="16">
              <a-button type="primary" @click="handleSearch(1)">
                <template #icon>
                  <icon-search />
                </template>
                查询
              </a-button>
              <a-button @click="$refs.refSearchForm.resetFields()">
                <template #icon>
                  <icon-refresh />
                </template>
                重置
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
      <a-divider style="margin-top: 0" />
      <a-space style="margin-bottom: 16px">
        <a-button size="small" type="primary" @click="handleEdit({})">
          <template #icon>
            <icon-plus />
          </template>
          新增
        </a-button>
      </a-space>
      <a-table
        bordered
        row-key="id"
        :data="tableData"
        :loading="pageLoading"
        :pagination="false"
      >
        <template #columns>
          <a-table-column title="ID" data-index="id"></a-table-column>
          <a-table-column title="数据名称" data-index="name"></a-table-column>
          <a-table-column title="数据值" data-index="value"></a-table-column>
          <a-table-column title="状态" data-index="status">
            <template #cell="{ record }">
              <DictBadge :options="statusOptions" :value="record.status"/>
            </template>
          </a-table-column>
          <a-table-column title="排序" data-index="sort"></a-table-column>
          <a-table-column title="备注" data-index="remark"></a-table-column>
          <a-table-column title="操作" :width="160">
            <template #cell="{ record }">
              <a-button type="text" @click="handleEdit(record)">编辑</a-button>
              <a-button type="text" @click="handleEdit(record)">新增</a-button>
              <a-popconfirm content="删除后不可恢复，确定要删除吗？" @ok="handleDelete(record)">
                <a-button v-if="record.id !== 10000" type="text" danger link>删除</a-button>
              </a-popconfirm>
            </template>
          </a-table-column>
        </template>

      </a-table>
    </a-card>

    <!-- 新增 & 编辑 弹窗 -->
    <a-modal
      v-model:visible="dialogVisible"
      width="680px"
      :title="`${formState.id ? '编辑' : '创建'}字典数据`"
      :footer="false">
      <a-form
        ref="formRef"
        :model="formState"
        :rules="formRules"
        auto-label-width
        @submit="handleSubmit"
      >
        <a-form-item field="dict_id" label="字典名称">
          <a-select
            v-model="formState.dict_id"
            :field-names="fieldNames"
            :options="dictOptions"
            placeholder="请输入字典名称"
          />
        </a-form-item>
        <a-form-item label="数据名称" field="name">
          <a-input v-model="formState.name" placeholder="请输入数据名称"></a-input>
        </a-form-item>

        <a-form-item label="数据值" field="value">
          <a-input v-model="formState.value" placeholder="请输入数据值"></a-input>
        </a-form-item>

        <a-form-item label="排序" field="sort">
          <a-input-number v-model="formState.sort" :min="1" :max="9999" />
        </a-form-item>

        <a-form-item label="状态" field="status">
          <a-radio-group v-model="formState.status">
            <a-radio v-for="item in statusOptions" :key="item.value" :value="item.value">{{ item.label }}</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="备注" field="remark">
          <a-textarea
            v-model="formState.remark"
            placeholder="简介"
            auto-size
            :maxlength="200"
            allow-clear
            show-word-limit
          />
        </a-form-item>
        <div class="form-footer">
          <a-button key="submit" html-type="submit" type="primary" :loading="pageLoading">确 定</a-button>
          <a-button class="ml-24" @click="handleCancel">取 消</a-button>
        </div>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import get from "lodash/get";
import { addDictData, delDictData, getDictDataList, getDictList, updateDictData } from "@/api/system/dict";
import { statusOptions } from "@/enums/status";

export default defineComponent({
  data() {
    return {
      pageLoading: false,
      statusOptions,
      tableData: [],
      // 搜索表单
      pageData: {
        pageSize: 50,
        current: 1,
        total: 0
      },
      searchForm: {
        dict_id: undefined,
        name: "",
        status: ""
      },
      dictOptions: [],
      fieldNames: {
        label: "name",
        value: "id"
      },
      // 创建弹窗
      dialogVisible: false,
      formState: {
        id: undefined,
        dict_id: undefined,
        name: undefined,
        value: undefined,
        sort: 1,
        status: 1,
        remark: undefined
      },
      formRules: {
        dict_id: [{ required: true, message: "字典名称不能为空", trigger: "change" }],
        name: [{ required: true, min: 2, message: "至少2个字符", trigger: "change" }],
        value: [{ required: true, min: 2, message: "至少2个字符", trigger: "change" }],
        sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
        status: [{ required: true, message: "状态不能为空", trigger: "blur" }]
      }
    };
  },
  mounted() {
    if (this.$route.query?.id) {
      this.searchForm.dict_id = Number(this.$route.query?.id);
    }
    this.fetchDictList();
    this.fetchTableData();
  },
  methods: {
    async fetchDictList(extraParam = {}) {
      this.pageLoading = true;
      try {
        let params = {
          pageSize: 50,
          current: 1
        };
        if (extraParam) {
          params = {
            ...params,
            ...extraParam
          };
        }
        const { data, code } = await getDictList(params);

        if (code === 200 && data) {
          this.dictOptions = get(data, "list", []);
        }
      } catch (err) {
        console.warn(err);
        // Message.error("出了点小问题，请稍后重试！");
      }
      this.pageLoading = false;
    },
    async fetchTableData(extraParam = {}) {
      this.pageLoading = true;
      try {
        let params = {
          ...this.pageData,
          ...this.searchForm
        };
        if (extraParam) {
          params = {
            ...params,
            ...extraParam
          };
        }
        const { data, code } = await getDictDataList(params);

        if (code === 200 && data) {
          this.tableData = get(data, "list", []);
          this.pageData.current = data.current || 0;
          this.pageData.total = data.total || 0;
        }
      } catch (err) {
        console.warn(err);
        // Message.error("出了点小问题，请稍后重试！");
      }
      this.pageLoading = false;
    },
    handleSearch(current: number) {
      this.fetchTableData({ current });
    },
    // 操作
    handleDelete(rowData) {
      if (!rowData.id) return;

      delDictData(rowData).then(res => {
        const { code, msg } = res;

        if (code === 200) {
          this.$message.success(msg || "删除成功！");
          this.fetchTableData();
        } else {
          this.$message.error(msg || "出了点小问题，请稍后重试！");
        }
      });
    },
    // 创建表单
    handleEdit(rowData: any) {
      this.dialogVisible = true;
      this.formState.dict_id = this.searchForm.dict_id || undefined;

      if (rowData.id) {
        this.formState = {
          id: rowData.id || undefined,
          dict_id: this.searchForm.dict_id || undefined,
          name: rowData.name || undefined,
          value: rowData.value || undefined,
          sort: rowData.sort || 1,
          status: rowData.status || 1,
          remark: rowData.remark || undefined
        };
      }
    },
    handleCancel() {
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
      this.dialogVisible = false;
    },
    async handleSubmit({ values, errors }) {
      console.log("values:", values, "\nerrors:", errors);
      if (!errors) {
        this.pageLoading = true;

        try {
          const params = {
            ...this.formState
          };
          let result = {};
          if (params.id) {
            result = await updateDictData(params);
          } else {
            result = await addDictData(params);
          }
          const { msg } = result;

          this.$message.success(msg || "创建成功！");
          await this.fetchTableData();
          this.handleCancel();
        } catch (err) {
          // you can report use errorHandler or other
        } finally {
          this.pageLoading = false;

        }
      }
    }
  }
});
</script>


<style scoped lang="less">
.form-footer {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
